import React, { useState, useMemo } from 'react';
import {
  Box,
  Card,
  CardContent,
  Typography,
  Button,
  TextField,
  InputAdornment,
  Select,
  MenuItem,
  FormControl,
  InputLabel,
  Chip,
  IconButton,
  Menu,
  MenuList,
  MenuItem as MenuOption,
  ListItemIcon,
  ListItemText,
  Alert,
  Avatar,
  Tooltip,
  Badge,
} from '@mui/material';
import {
  DataGrid,
  GridColDef,
  GridRenderCellParams,
  GridToolbar,
  GridActionsCellItem,
} from '@mui/x-data-grid';
import {
  Search as SearchIcon,
  Add as AddIcon,
  FilterList as FilterIcon,
  Edit as EditIcon,
  Delete as DeleteIcon,
  MoreVert as MoreVertIcon,
  Visibility as ViewIcon,
  Person as PersonIcon,
  Email as EmailIcon,
  Phone as PhoneIcon,
  Business as BusinessIcon,
  Security as SecurityIcon,
  Block as BlockIcon,
  CheckCircle as CheckCircleIcon,
  Warning as WarningIcon,
} from '@mui/icons-material';
import { useNavigate } from 'react-router-dom';
import { useQuery, useMutation, useQueryClient } from '@tanstack/react-query';

import { 
  User, 
  UserFilter, 
  Status,
  PaginatedResponse,
} from '@/types';
import { useAuth, useAppNotifications } from '@/stores';
import { userService } from '@/services/userService';
import { PageHeader } from '@/components/common/PageHeader';

const UserListPage: React.FC = () => {
  const navigate = useNavigate();
  const queryClient = useQueryClient();
  const { hasPermission, currentTenant, currentOrganization } = useAuth();
  const { showToast } = useAppNotifications();

  // 状态管理
  const [searchQuery, setSearchQuery] = useState('');
  const [statusFilter, setStatusFilter] = useState<Status | ''>('');
  const [organizationFilter, setOrganizationFilter] = useState('');
  const [roleFilter, setRoleFilter] = useState('');
  const [page, setPage] = useState(0);
  const [pageSize, setPageSize] = useState(25);
  const [selectedRows, setSelectedRows] = useState<string[]>([]);
  const [actionMenuAnchor, setActionMenuAnchor] = useState<null | HTMLElement>(null);
  const [selectedUser, setSelectedUser] = useState<User | null>(null);

  // 构建查询参数
  const queryParams = useMemo(() => {
    const params: UserFilter & { page: number; pageSize: number } = {
      page: page + 1,
      pageSize,
    };

    if (currentTenant) {
      params.tenantId = currentTenant.id;
    }
    if (currentOrganization) {
      params.organizationId = currentOrganization.id;
    }
    if (searchQuery.trim()) {
      params.search = searchQuery.trim();
    }
    if (statusFilter) {
      params.status = statusFilter;
    }
    if (organizationFilter) {
      params.organizationId = organizationFilter;
    }
    if (roleFilter) {
      params.roleId = roleFilter;
    }

    return params;
  }, [searchQuery, statusFilter, organizationFilter, roleFilter, page, pageSize, currentTenant, currentOrganization]);

  // 获取用户列表
  const {
    data: userData,
    isLoading,
    error,
    refetch,
  } = useQuery({
    queryKey: ['users', queryParams],
    queryFn: () => userService.getUsers(queryParams),
    keepPreviousData: true,
    enabled: !!currentTenant,
  });

  // 获取组织列表（用于筛选）
  const { data: organizationsData } = useQuery({
    queryKey: ['organizations', { tenantId: currentTenant?.id }],
    queryFn: () => fetch(`/api/organizations?tenantId=${currentTenant?.id}`).then(res => res.json()),
    enabled: !!currentTenant,
  });

  // 获取角色列表（用于筛选）
  const { data: rolesData } = useQuery({
    queryKey: ['roles', { tenantId: currentTenant?.id }],
    queryFn: () => fetch(`/api/roles?tenantId=${currentTenant?.id}`).then(res => res.json()),
    enabled: !!currentTenant,
  });

  // 删除用户
  const deleteMutation = useMutation({
    mutationFn: userService.deleteUser,
    onSuccess: () => {
      showToast({
        type: 'success',
        title: '删除成功',
        message: '用户已成功删除',
      });
      queryClient.invalidateQueries(['users']);
    },
    onError: (error: any) => {
      showToast({
        type: 'error',
        title: '删除失败',
        message: error.message || '删除用户时发生错误',
      });
    },
  });

  // 批量删除用户
  const batchDeleteMutation = useMutation({
    mutationFn: (ids: string[]) => userService.batchDeleteUsers(ids),
    onSuccess: () => {
      showToast({
        type: 'success',
        title: '批量删除成功',
        message: `成功删除 ${selectedRows.length} 个用户`,
      });
      setSelectedRows([]);
      queryClient.invalidateQueries(['users']);
    },
    onError: (error: any) => {
      showToast({
        type: 'error',
        title: '批量删除失败',
        message: error.message || '批量删除用户时发生错误',
      });
    },
  });

  // 启用/禁用用户
  const toggleStatusMutation = useMutation({
    mutationFn: ({ id, status }: { id: string; status: Status }) => 
      userService.updateUser(id, { status }),
    onSuccess: () => {
      showToast({
        type: 'success',
        title: '操作成功',
        message: '用户状态已更新',
      });
      queryClient.invalidateQueries(['users']);
    },
    onError: (error: any) => {
      showToast({
        type: 'error',
        title: '操作失败',
        message: error.message || '更新用户状态时发生错误',
      });
    },
  });

  // 渲染用户状态
  const renderStatus = (status: Status) => {
    const statusConfig = {
      active: { label: '启用', color: 'success' as const, icon: <CheckCircleIcon /> },
      inactive: { label: '禁用', color: 'error' as const, icon: <BlockIcon /> },
      pending: { label: '待审核', color: 'warning' as const, icon: <WarningIcon /> },
      suspended: { label: '暂停', color: 'error' as const, icon: <BlockIcon /> },
    };

    const config = statusConfig[status] || statusConfig.inactive;
    return (
      <Chip 
        label={config.label} 
        color={config.color} 
        size="small" 
        icon={config.icon}
      />
    );
  };

  // 渲染用户角色
  const renderRoles = (roles: string[]) => {
    if (!roles || roles.length === 0) return '-';
    
    const displayRoles = roles.slice(0, 2);
    const remainingCount = roles.length - 2;
    
    return (
      <Box sx={{ display: 'flex', gap: 0.5, flexWrap: 'wrap' }}>
        {displayRoles.map((roleId, index) => {
          const role = rolesData?.find((r: any) => r.id === roleId);
          return (
            <Chip
              key={roleId}
              label={role?.name || roleId}
              size="small"
              variant="outlined"
              color="primary"
            />
          );
        })}
        {remainingCount > 0 && (
          <Chip
            label={`+${remainingCount}`}
            size="small"
            variant="outlined"
            color="default"
          />
        )}
      </Box>
    );
  };

  // 表格列定义
  const columns: GridColDef[] = [
    {
      field: 'profile',
      headerName: '用户信息',
      flex: 1,
      minWidth: 250,
      renderCell: (params: GridRenderCellParams<User>) => (
        <Box sx={{ display: 'flex', alignItems: 'center', gap: 2, py: 1 }}>
          <Badge
            overlap="circular"
            anchorOrigin={{ vertical: 'bottom', horizontal: 'right' }}
            badgeContent={
              params.row.status === 'active' ? (
                <CheckCircleIcon sx={{ color: 'success.main', fontSize: 16 }} />
              ) : (
                <BlockIcon sx={{ color: 'error.main', fontSize: 16 }} />
              )
            }
          >
            <Avatar
              src={params.row.profile.avatar}
              alt={params.row.profile.fullName}
              sx={{ width: 40, height: 40 }}
            >
              {params.row.profile.fullName?.charAt(0) || params.row.username.charAt(0).toUpperCase()}
            </Avatar>
          </Badge>
          <Box sx={{ minWidth: 0, flex: 1 }}>
            <Typography variant="subtitle2" noWrap>
              {params.row.profile.fullName}
            </Typography>
            <Typography variant="caption" color="text.secondary" noWrap>
              {params.row.username}
            </Typography>
            <Box sx={{ display: 'flex', alignItems: 'center', gap: 1, mt: 0.5 }}>
              {params.row.profile.email && (
                <Tooltip title={params.row.profile.email}>
                  <EmailIcon sx={{ fontSize: 14, color: 'text.secondary' }} />
                </Tooltip>
              )}
              {params.row.profile.phone && (
                <Tooltip title={params.row.profile.phone}>
                  <PhoneIcon sx={{ fontSize: 14, color: 'text.secondary' }} />
                </Tooltip>
              )}
            </Box>
          </Box>
        </Box>
      ),
    },
    {
      field: 'roles',
      headerName: '角色',
      width: 200,
      renderCell: (params: GridRenderCellParams<User>) => 
        renderRoles(params.row.roles),
    },
    {
      field: 'organizationId',
      headerName: '所属组织',
      width: 150,
      renderCell: (params: GridRenderCellParams<User>) => {
        const org = organizationsData?.data?.find((o: any) => o.id === params.row.organizationId);
        return (
          <Box sx={{ display: 'flex', alignItems: 'center', gap: 1 }}>
            <BusinessIcon fontSize="small" color="primary" />
            <Typography variant="body2" noWrap>
              {org?.name || '-'}
            </Typography>
          </Box>
        );
      },
    },
    {
      field: 'status',
      headerName: '状态',
      width: 100,
      renderCell: (params: GridRenderCellParams<User>) => 
        renderStatus(params.row.status),
    },
    {
      field: 'lastLoginAt',
      headerName: '最后登录',
      width: 150,
      valueGetter: (params) => 
        params.row.lastLoginAt 
          ? new Date(params.row.lastLoginAt).toLocaleDateString()
          : '从未登录',
    },
    {
      field: 'createdAt',
      headerName: '创建时间',
      width: 150,
      valueGetter: (params) => new Date(params.row.createdAt).toLocaleDateString(),
    },
    {
      field: 'actions',
      type: 'actions',
      headerName: '操作',
      width: 120,
      getActions: (params: GridRenderCellParams<User>) => {
        const actions = [];

        if (hasPermission('user.view')) {
          actions.push(
            <GridActionsCellItem
              icon={<ViewIcon />}
              label="查看"
              onClick={() => navigate(`/users/${params.row.id}`)}
            />
          );
        }

        if (hasPermission('user.edit')) {
          actions.push(
            <GridActionsCellItem
              icon={<EditIcon />}
              label="编辑"
              onClick={() => navigate(`/users/${params.row.id}/edit`)}
            />
          );
        }

        if (hasPermission('user.delete')) {
          actions.push(
            <GridActionsCellItem
              icon={<DeleteIcon />}
              label="删除"
              onClick={() => handleDeleteUser(params.row)}
            />
          );
        }

        actions.push(
          <GridActionsCellItem
            icon={<MoreVertIcon />}
            label="更多"
            onClick={(event) => handleMoreActions(event, params.row)}
          />
        );

        return actions;
      },
    },
  ];

  // 处理删除用户
  const handleDeleteUser = (user: User) => {
    if (window.confirm(`确定要删除用户"${user.profile.fullName}"吗？此操作不可撤销。`)) {
      deleteMutation.mutate(user.id);
    }
  };

  // 处理更多操作菜单
  const handleMoreActions = (event: React.MouseEvent<HTMLButtonElement>, user: User) => {
    event.stopPropagation();
    setActionMenuAnchor(event.currentTarget);
    setSelectedUser(user);
  };

  // 关闭操作菜单
  const handleCloseActionMenu = () => {
    setActionMenuAnchor(null);
    setSelectedUser(null);
  };

  // 处理批量删除
  const handleBatchDelete = () => {
    if (window.confirm(`确定要删除选中的 ${selectedRows.length} 个用户吗？此操作不可撤销。`)) {
      batchDeleteMutation.mutate(selectedRows);
    }
  };

  // 处理状态切换
  const handleToggleStatus = (user: User) => {
    const newStatus = user.status === 'active' ? 'inactive' : 'active';
    toggleStatusMutation.mutate({ id: user.id, status: newStatus });
    handleCloseActionMenu();
  };

  // 清除筛选
  const handleClearFilters = () => {
    setSearchQuery('');
    setStatusFilter('');
    setOrganizationFilter('');
    setRoleFilter('');
  };

  if (!currentTenant) {
    return (
      <Box sx={{ p: 3 }}>
        <Alert severity="warning">
          请先选择租户
        </Alert>
      </Box>
    );
  }

  if (error) {
    return (
      <Box sx={{ p: 3 }}>
        <Alert severity="error">
          加载用户列表失败：{(error as any).message}
        </Alert>
      </Box>
    );
  }

  return (
    <Box sx={{ p: 3 }}>
      <PageHeader
        title="用户管理"
        description="管理系统用户和权限分配"
        actions={
          hasPermission('user.create') ? (
            <Button
              variant="contained"
              startIcon={<AddIcon />}
              onClick={() => navigate('/users/create')}
            >
              创建用户
            </Button>
          ) : undefined
        }
      />

      <Card>
        <CardContent>
          {/* 筛选工具栏 */}
          <Box sx={{ mb: 3, display: 'flex', gap: 2, flexWrap: 'wrap', alignItems: 'center' }}>
            <TextField
              placeholder="搜索用户名、姓名或邮箱..."
              value={searchQuery}
              onChange={(e) => setSearchQuery(e.target.value)}
              InputProps={{
                startAdornment: (
                  <InputAdornment position="start">
                    <SearchIcon />
                  </InputAdornment>
                ),
              }}
              sx={{ minWidth: 300 }}
            />

            <FormControl sx={{ minWidth: 120 }}>
              <InputLabel>状态</InputLabel>
              <Select
                value={statusFilter}
                label="状态"
                onChange={(e) => setStatusFilter(e.target.value as Status)}
              >
                <MenuItem value="">全部</MenuItem>
                <MenuItem value="active">启用</MenuItem>
                <MenuItem value="inactive">禁用</MenuItem>
                <MenuItem value="pending">待审核</MenuItem>
                <MenuItem value="suspended">暂停</MenuItem>
              </Select>
            </FormControl>

            <FormControl sx={{ minWidth: 140 }}>
              <InputLabel>组织</InputLabel>
              <Select
                value={organizationFilter}
                label="组织"
                onChange={(e) => setOrganizationFilter(e.target.value)}
              >
                <MenuItem value="">全部</MenuItem>
                {organizationsData?.data?.map((org: any) => (
                  <MenuItem key={org.id} value={org.id}>
                    {org.name}
                  </MenuItem>
                ))}
              </Select>
            </FormControl>

            <FormControl sx={{ minWidth: 120 }}>
              <InputLabel>角色</InputLabel>
              <Select
                value={roleFilter}
                label="角色"
                onChange={(e) => setRoleFilter(e.target.value)}
              >
                <MenuItem value="">全部</MenuItem>
                {rolesData?.map((role: any) => (
                  <MenuItem key={role.id} value={role.id}>
                    {role.name}
                  </MenuItem>
                ))}
              </Select>
            </FormControl>

            <Button
              variant="outlined"
              startIcon={<FilterIcon />}
              onClick={handleClearFilters}
            >
              清除筛选
            </Button>

            {selectedRows.length > 0 && hasPermission('user.delete') && (
              <Button
                variant="outlined"
                color="error"
                startIcon={<DeleteIcon />}
                onClick={handleBatchDelete}
                disabled={batchDeleteMutation.isLoading}
              >
                批量删除 ({selectedRows.length})
              </Button>
            )}
          </Box>

          {/* 数据表格 */}
          <Box sx={{ height: 600 }}>
            <DataGrid
              rows={userData?.data || []}
              columns={columns}
              loading={isLoading}
              paginationMode="server"
              rowCount={userData?.pagination?.total || 0}
              page={page}
              pageSize={pageSize}
              onPageChange={setPage}
              onPageSizeChange={setPageSize}
              pageSizeOptions={[10, 25, 50, 100]}
              checkboxSelection={hasPermission('user.delete')}
              disableRowSelectionOnClick
              rowSelectionModel={selectedRows}
              onRowSelectionModelChange={(newSelection) => {
                setSelectedRows(newSelection as string[]);
              }}
              slots={{
                toolbar: GridToolbar,
              }}
              slotProps={{
                toolbar: {
                  showQuickFilter: true,
                  quickFilterProps: { debounceMs: 500 },
                },
              }}
              sx={{
                '& .MuiDataGrid-row:hover': {
                  backgroundColor: 'action.hover',
                },
              }}
            />
          </Box>
        </CardContent>
      </Card>

      {/* 更多操作菜单 */}
      <Menu
        anchorEl={actionMenuAnchor}
        open={Boolean(actionMenuAnchor)}
        onClose={handleCloseActionMenu}
        PaperProps={{
          sx: { minWidth: 180 },
        }}
      >
        <MenuList>
          <MenuOption onClick={() => {
            if (selectedUser) {
              navigate(`/users/${selectedUser.id}`);
            }
            handleCloseActionMenu();
          }}>
            <ListItemIcon>
              <ViewIcon />
            </ListItemIcon>
            <ListItemText primary="查看详情" />
          </MenuOption>
          
          {hasPermission('user.edit') && (
            <MenuOption onClick={() => {
              if (selectedUser) {
                navigate(`/users/${selectedUser.id}/edit`);
              }
              handleCloseActionMenu();
            }}>
              <ListItemIcon>
                <EditIcon />
              </ListItemIcon>
              <ListItemText primary="编辑用户" />
            </MenuOption>
          )}
          
          {hasPermission('user.edit') && selectedUser && (
            <MenuOption onClick={() => handleToggleStatus(selectedUser)}>
              <ListItemIcon>
                {selectedUser.status === 'active' ? <BlockIcon /> : <CheckCircleIcon />}
              </ListItemIcon>
              <ListItemText 
                primary={selectedUser.status === 'active' ? '禁用用户' : '启用用户'} 
              />
            </MenuOption>
          )}
          
          {hasPermission('user.edit') && (
            <MenuOption onClick={() => {
              if (selectedUser) {
                navigate(`/users/${selectedUser.id}/security`);
              }
              handleCloseActionMenu();
            }}>
              <ListItemIcon>
                <SecurityIcon />
              </ListItemIcon>
              <ListItemText primary="安全设置" />
            </MenuOption>
          )}
        </MenuList>
      </Menu>
    </Box>
  );
};

export default UserListPage;